<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="用户姓名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工资年份" prop="salaryYear">
        <el-select
          v-model="queryParams.salaryYear"
          placeholder="请选择工资年份"
          clearable
          style="width: 180px">
          <el-option 
            v-for="year in yearOptions" 
            :key="year" 
            :label="year + '年'" 
            :value="year">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工资月份" prop="salaryMonth">
        <el-select
          v-model="queryParams.salaryMonth"
          placeholder="请选择工资月份"
          clearable
          style="width: 180px">
          <el-option 
            v-for="month in monthOptions" 
            :key="month" 
            :label="month + '月'" 
            :value="month">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          style="width: 180px">
          <el-option 
            v-for="item in statusOptions" 
            :key="item.value" 
            :label="item.label" 
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="基本工资" prop="baseSalary">
        <el-input
          v-model="queryParams.baseSalary"
          placeholder="请输入基本工资"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="绩效考核" prop="performanceBonus">
        <el-input
          v-model="queryParams.performanceBonus"
          placeholder="请输入绩效考核"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="奖金" prop="bonus">
        <el-input
          v-model="queryParams.bonus"
          placeholder="请输入奖金"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="全勤" prop="fullAttendance">
        <el-input
          v-model="queryParams.fullAttendance"
          placeholder="请输入全勤"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="提成" prop="commission">
        <el-input
          v-model="queryParams.commission"
          placeholder="请输入提成"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="扣款" prop="deduction">
        <el-input
          v-model="queryParams.deduction"
          placeholder="请输入扣款"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="补助" prop="allowance">
        <el-input
          v-model="queryParams.allowance"
          placeholder="请输入补助"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="五险扣款" prop="insuranceDeduction">
        <el-input
          v-model="queryParams.insuranceDeduction"
          placeholder="请输入五险扣款"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="综合工资" prop="totalSalary">
        <el-input
          v-model="queryParams.totalSalary"
          placeholder="请输入综合工资"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发放日期" prop="payDate">
        <el-date-picker clearable
          v-model="queryParams.payDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择发放日期">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['preSalary:preSalary:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['preSalary:preSalary:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['preSalary:preSalary:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['preSalary:preSalary:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-circle-plus-outline"
          size="mini"
          @click="handleCreateMonthlyRecords"
          v-hasPermi="['preSalary:preSalary:add']"
        >创建当月工资</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="preSalaryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键ID" align="center" prop="id" /> -->
      <!-- <el-table-column label="用户ID" align="center" prop="userId" /> -->
      <el-table-column label="用户姓名" align="center" prop="userName" />
      <el-table-column label="工资年份" align="center" prop="salaryYear" />
      <el-table-column label="工资月份" align="center" prop="salaryMonth" />
      <el-table-column label="基本工资" align="center" prop="baseSalary" />
      <el-table-column label="绩效考核" align="center" prop="performanceBonus" />
      <el-table-column label="奖金" align="center" prop="bonus" />
      <el-table-column label="全勤" align="center" prop="fullAttendance" />
      <el-table-column label="提成" align="center" prop="commission" />
      <el-table-column label="扣款" align="center" prop="deduction" />
      <el-table-column label="补助" align="center" prop="allowance" />
      <el-table-column label="五险扣款" align="center" prop="insuranceDeduction" />
      <el-table-column label="综合工资" align="center" prop="totalSalary" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag 
            :type="getStatusTagType(scope.row.status)"
            size="mini">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="发放日期" align="center" prop="payDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.payDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="280">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['preSalary:preSalary:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['preSalary:preSalary:remove']"
          >删除</el-button>
          <el-dropdown size="mini" @command="(command) => handleStatusChange(scope.row, command)" v-hasPermi="['preSalary:preSalary:edit']">
            <el-button size="mini" type="text">
              状态<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="0" :disabled="scope.row.status === '0'">
                <i class="el-icon-circle-check" style="color: #67C23A;"></i> 设为正常
              </el-dropdown-item>
              <el-dropdown-item command="1" :disabled="scope.row.status === '1'">
                <i class="el-icon-circle-close" style="color: #F56C6C;"></i> 设为停用
              </el-dropdown-item>
              <el-dropdown-item command="2" :disabled="scope.row.status === '2'">
                <i class="el-icon-success" style="color: #909399;"></i> 设为已发放
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改售前工资管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body class="salary-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" class="salary-form">
        <!-- 基本信息区域 -->
        <div class="form-section">
          <div class="section-title">
            <i class="el-icon-date" style="color: #409EFF;"></i>
            <span>基本信息</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="工资年份" prop="salaryYear">
                <el-select v-model="form.salaryYear" placeholder="请选择工资年份" style="width: 100%">
                  <el-option 
                    v-for="year in yearOptions" 
                    :key="year" 
                    :label="year + '年'" 
                    :value="year">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工资月份" prop="salaryMonth">
                <el-select v-model="form.salaryMonth" placeholder="请选择工资月份" style="width: 100%">
                  <el-option 
                    v-for="month in monthOptions" 
                    :key="month" 
                    :label="month + '月'" 
                    :value="month">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 出勤信息区域 -->
        <div class="form-section">
          <div class="section-title">
            <i class="el-icon-time" style="color: #E6A23C;"></i>
            <span>出勤信息</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="应出勤天数" prop="requiredAttendanceDays">
                <el-input-number 
                  v-model="form.requiredAttendanceDays" 
                  :precision="1" 
                  :step="0.5" 
                  :min="1"
                  :max="31"
                  controls-position="right"
                  style="width: 100%" 
                  placeholder="22.0" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="实际出勤天数" prop="actualAttendanceDays">
                <el-input-number 
                  v-model="form.actualAttendanceDays" 
                  :precision="1" 
                  :step="0.5" 
                  :min="0"
                  :max="31"
                  controls-position="right"
                  style="width: 100%" 
                  placeholder="22.0" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="日工资">
                <el-input 
                  :value="calculatedDailySalary" 
                  readonly 
                  class="daily-salary-input"
                  placeholder="自动计算">
                  <template slot="prepend">￥</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 工资构成区域 -->
        <div class="form-section">
          <div class="section-title">
            <i class="el-icon-money" style="color: #67C23A;"></i>
            <span>工资构成</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item prop="monthlySalary">
                <div slot="label" class="basic-label">
                  <i class="el-icon-wallet" style="color: #409EFF;"></i>
                  月薪
                  <el-button 
                    type="text" 
                    size="mini" 
                    @click="syncBaseSalaryToMonthlySalary" 
                    style="margin-left: 8px; color: #409EFF;"
                    title="使用基本工资填充月薪">
                    <i class="el-icon-refresh"></i>
                  </el-button>
                </div>
                <el-input-number 
                  v-model="form.monthlySalary" 
                  :precision="2" 
                  :step="100" 
                  :min="0"
                  controls-position="right"
                  style="width: 100%" 
                  placeholder="0.00" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="baseSalary">
                <div slot="label" class="calculated-label">
                  <i class="el-icon-s-finance" style="color: #E6A23C;"></i>
                  实际基资
                </div>
                <el-input 
                  :value="calculatedBaseSalary" 
                  readonly 
                  class="calculated-salary-input"
                  placeholder="自动计算">
                  <template slot="prepend">￥</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="performanceBonus">
                <div slot="label" class="neutral-label">
                  <i class="el-icon-star-on" style="color: #E6A23C;"></i>
                  绩效考核
                </div>
                <el-input-number 
                  v-model="form.performanceBonus" 
                  :precision="2" 
                  :step="100" 
                  controls-position="right"
                  style="width: 100%" 
                  placeholder="0.00" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item prop="bonus">
                <div slot="label" class="positive-label">
                  <i class="el-icon-plus" style="color: #67C23A;"></i>
                  奖金
                </div>
                <el-input-number 
                  v-model="form.bonus" 
                  :precision="2" 
                  :step="100" 
                  :min="0"
                  controls-position="right"
                  style="width: 100%" 
                  placeholder="0.00" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="fullAttendance">
                <div slot="label" class="neutral-label">
                  <i class="el-icon-star-on" style="color: #E6A23C;"></i>
                  全勤
                </div>
                <el-input-number 
                  v-model="form.fullAttendance" 
                  :precision="2" 
                  :step="100" 
                  controls-position="right"
                  style="width: 100%" 
                  placeholder="0.00" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item prop="commission">
                <div slot="label" class="positive-label">
                  <i class="el-icon-plus" style="color: #67C23A;"></i>
                  提成
                </div>
                <el-input-number 
                  v-model="form.commission" 
                  :precision="2" 
                  :step="100" 
                  :min="0"
                  controls-position="right"
                  style="width: 100%" 
                  placeholder="0.00" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="allowance">
                <div slot="label" class="positive-label">
                  <i class="el-icon-plus" style="color: #67C23A;"></i>
                  补助
                </div>
                <el-input-number 
                  v-model="form.allowance" 
                  :precision="2" 
                  :step="100" 
                  :min="0"
                  controls-position="right"
                  style="width: 100%" 
                  placeholder="0.00" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 扣除项目区域 -->
        <div class="form-section">
          <div class="section-title">
            <i class="el-icon-remove" style="color: #F56C6C;"></i>
            <span>扣除项目</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item prop="deduction">
                <div slot="label" class="negative-label">
                  <i class="el-icon-minus" style="color: #F56C6C;"></i>
                  扣款
                </div>
                <el-input-number 
                  v-model="form.deduction" 
                  :precision="2" 
                  :step="100" 
                  :min="0"
                  controls-position="right"
                  style="width: 100%" 
                  placeholder="0.00" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="insuranceDeduction">
                <div slot="label" class="negative-label">
                  <i class="el-icon-minus" style="color: #F56C6C;"></i>
                  五险扣款
                </div>
                <el-input-number 
                  v-model="form.insuranceDeduction" 
                  :precision="2" 
                  :step="100" 
                  :min="0"
                  controls-position="right"
                  style="width: 100%" 
                  placeholder="0.00" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 计算结果区域 -->
        <div class="form-section total-section">
          <div class="section-title">
            <i class="el-icon-coin" style="color: #E6A23C;"></i>
            <span>计算结果</span>
          </div>
          <el-form-item prop="totalSalary">
            <div slot="label" class="total-label">
              <i class="el-icon-s-finance" style="color: #E6A23C;"></i>
              综合工资
            </div>
            <el-input 
              :value="calculatedTotalSalary" 
              readonly 
              class="total-salary-input"
              placeholder="自动计算">
              <template slot="prepend">￥</template>
            </el-input>
          </el-form-item>
        </div>

        <!-- 备注区域 -->
        <div class="form-section">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPreSalary, getPreSalary, delPreSalary, addPreSalary, updatePreSalary, createMonthlySalaryRecords } from "@/api/preSalary/preSalary"

export default {
  name: "PreSalary",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 售前工资管理表格数据
      preSalaryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        userName: null,
        salaryYear: new Date().getFullYear(),
        salaryMonth: new Date().getMonth() + 1,
        baseSalary: null,
        performanceBonus: null,
        bonus: null,
        fullAttendance: null,
        commission: null,
        deduction: null,
        allowance: null,
        insuranceDeduction: null,
        totalSalary: null,
        status: null,
        payDate: null,
      },
      // 状态选项
      statusOptions: [
        { label: '正常', value: '0' },
        { label: '停用', value: '1' },
        { label: '已发放', value: '2' }
      ],
      // 表单参数
      form: {},
      // 年份选项（前后三年）
      yearOptions: [],
      // 月份选项（1-12月）
      monthOptions: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
      // 表单校验
      rules: {
        salaryYear: [
          { required: true, message: "工资年份不能为空", trigger: "change" }
        ],
        salaryMonth: [
          { required: true, message: "工资月份不能为空", trigger: "change" }
        ],
      }
    }
  },
  computed: {
    // 计算日工资：月薪 ÷ 应出勤天数
    calculatedDailySalary() {
      const { monthlySalary = 0, requiredAttendanceDays = 22 } = this.form;
      if (requiredAttendanceDays === 0) return '0.00';
      
      // 支持小数的应出勤天数计算
      const monthlyAmount = parseFloat(monthlySalary);
      const requiredDays = parseFloat(requiredAttendanceDays);
      const dailySalary = requiredDays !== 0 ? monthlyAmount / requiredDays : 0;
      
      return dailySalary.toFixed(2);
    },
    
    // 计算实际基本工资：日工资 × 实际出勤天数
    calculatedBaseSalary() {
      const { monthlySalary = 0, requiredAttendanceDays = 22, actualAttendanceDays = 22 } = this.form;
      
      // 特殊情况：当应出勤天数等于实际出勤天数时，直接返回月薪，避免精度问题
      if (parseFloat(requiredAttendanceDays) === parseFloat(actualAttendanceDays)) {
        return parseFloat(monthlySalary).toFixed(2);
      }
      
      // 一般情况：按比例计算
      if (requiredAttendanceDays === 0) return '0.00';
      
      // 使用月薪直接按比例计算，支持小数出勤天数
      const monthlyAmount = Math.round(parseFloat(monthlySalary) * 100); // 转换为分，避免浮点数精度问题
      const actualDays = parseFloat(actualAttendanceDays); // 支持小数天数
      const requiredDays = parseFloat(requiredAttendanceDays);
      const baseAmount = Math.round((monthlyAmount * actualDays) / requiredDays);
      
      return (baseAmount / 100).toFixed(2);
    },

    // 自动计算综合工资：实际基本工资 + 其他项目 - 扣除项目
    calculatedTotalSalary() {
      const {
        performanceBonus = 0,
        bonus = 0,
        fullAttendance = 0,
        commission = 0,
        deduction = 0,
        allowance = 0,
        insuranceDeduction = 0
      } = this.form;
      
      const baseSalary = parseFloat(this.calculatedBaseSalary);
      const total = (
        baseSalary +
        parseFloat(performanceBonus) +
        parseFloat(bonus) +
        parseFloat(fullAttendance) +
        parseFloat(commission) +
        parseFloat(allowance) -
        parseFloat(deduction) -
        parseFloat(insuranceDeduction)
      );
      
      return total.toFixed(2);
    }
  },
  watch: {
    // 监听计算结果，自动更新基本工资
    calculatedBaseSalary(newVal) {
      this.form.baseSalary = parseFloat(newVal);
    },
    // 监听计算结果，自动更新总工资
    calculatedTotalSalary(newVal) {
      this.form.totalSalary = parseFloat(newVal);
    },
    // 监听基本工资变化，同步更新月薪（在新增模式下）
    'form.baseSalary'(newVal) {
      // 如果是新增模式（没有id）且月薪为0或未设置，则同步基本工资到月薪
      if (!this.form.id && (!this.form.monthlySalary || this.form.monthlySalary === 0)) {
        this.form.monthlySalary = parseFloat(newVal) || 0;
      }
    }
  },
  created() {
    this.initYearOptions()
    this.getList()
  },
  methods: {
    // 精确计算工具函数：避免浮点数精度问题
    preciseCalculate(num1, num2, operation) {
      const factor = 10000; // 提高精度到4位小数
      const n1 = Math.round(parseFloat(num1) * factor);
      const n2 = parseFloat(num2);
      
      let result;
      switch (operation) {
        case 'multiply':
          result = (n1 * n2) / factor;
          break;
        case 'divide':
          result = n2 !== 0 ? n1 / (n2 * factor) : 0;
          break;
        case 'add':
          const n2_scaled = Math.round(n2 * factor);
          result = (n1 + n2_scaled) / factor;
          break;
        case 'subtract':
          const n2_scaled_sub = Math.round(n2 * factor);
          result = (n1 - n2_scaled_sub) / factor;
          break;
        default:
          result = 0;
      }
      
      return Math.round(result * 100) / 100; // 最终保留两位小数
    },
    // 初始化年份选项（前后三年）
    initYearOptions() {
      const currentYear = new Date().getFullYear()
      this.yearOptions = []
      for (let i = currentYear - 3; i <= currentYear + 3; i++) {
        this.yearOptions.push(i)
      }
    },
    /** 查询售前工资管理列表 */
    getList() {
      this.loading = true
      listPreSalary(this.queryParams).then(response => {
        this.preSalaryList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      const currentDate = new Date()
      this.form = {
        id: null,
        userId: null,
        userName: null,
        salaryYear: currentDate.getFullYear(),
        salaryMonth: currentDate.getMonth() + 1,
        requiredAttendanceDays: 22.0,
        actualAttendanceDays: 22.0,
        monthlySalary: 0,
        baseSalary: 0,
        performanceBonus: 0,
        bonus: 0,
        fullAttendance: 0,
        commission: 0,
        deduction: 0,
        allowance: 0,
        insuranceDeduction: 0,
        totalSalary: 0,
        status: null,
        remark: null,
        payDate: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      // 在新增时，如果基本工资有值，将月薪设置为基本工资的值
      if (this.form.baseSalary && this.form.baseSalary > 0) {
        this.form.monthlySalary = this.form.baseSalary
      }
      this.open = true
      this.title = "添加售前工资管理"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getPreSalary(id).then(response => {
        this.form = response.data
        // 设置月薪等于基本工资（按照用户需求）
        if (this.form.baseSalary) {
          this.form.monthlySalary = this.form.baseSalary
        }
        // 如果没有出勤天数数据，设置默认值
        if (!this.form.requiredAttendanceDays) {
          this.form.requiredAttendanceDays = 22.0
        }
        if (!this.form.actualAttendanceDays) {
          this.form.actualAttendanceDays = 22.0
        }
        this.open = true
        this.title = "修改售前工资管理"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePreSalary(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addPreSalary(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除售前工资管理编号为"' + ids + '"的数据项？').then(function() {
        return delPreSalary(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('preSalary/preSalary/export', {
        ...this.queryParams
      }, `preSalary_${new Date().getTime()}.xlsx`)
    },
    // 获取状态显示文字
    getStatusText(status) {
      const statusItem = this.statusOptions.find(item => item.value === status)
      return statusItem ? statusItem.label : '未知'
    },
    // 获取状态标签类型
    getStatusTagType(status) {
      switch(status) {
        case '0': return 'success'  // 正常 - 绿色
        case '1': return 'danger'   // 停用 - 红色
        case '2': return 'info'     // 已发放 - 蓝色
        default: return ''          // 默认
      }
    },
    // 处理状态变更
    handleStatusChange(row, newStatus) {
      const statusText = this.getStatusText(newStatus)
      this.$modal.confirm('确认要将"' + row.userName + '"的状态修改为"' + statusText + '"吗？').then(() => {
        const updateData = {
          id: row.id,
          status: newStatus
        }
        updatePreSalary(updateData).then(response => {
          this.$modal.msgSuccess("状态修改成功")
          this.getList()
        }).catch(error => {
          this.$modal.msgError("状态修改失败")
        })
      }).catch(() => {})
    },
    // 同步基本工资到月薪
    syncBaseSalaryToMonthlySalary() {
      if (this.form.baseSalary && this.form.baseSalary > 0) {
        this.form.monthlySalary = this.form.baseSalary
        this.$message.success('已将基本工资同步到月薪')
      } else {
        this.$message.warning('基本工资为空或为0，无法同步')
      }
    },
    /** 手动创建当月工资记录 */
    handleCreateMonthlyRecords() {
      this.$modal.confirm('确认要创建当月工资记录吗？系统将为所有售前人员自动生成本月的工资记录。').then(() => {
        this.loading = true
        createMonthlySalaryRecords().then(response => {
          this.$modal.msgSuccess(response.msg || "创建成功")
          this.getList()
        }).catch(() => {
          this.loading = false
        })
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
/* 薪资对话框样式 */
.salary-dialog .el-dialog__body {
  padding: 10px 20px;
}

.salary-form {
  max-height: 70vh;
  overflow-y: auto;
}

/* 表单区域样式 */
.form-section {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #EBEEF5;
  border-radius: 6px;
  background-color: #FAFAFA;
}

.form-section:last-child {
  margin-bottom: 0;
}

/* 区域标题样式 */
.section-title {
  margin-bottom: 15px;
  padding-bottom: 8px;
  border-bottom: 2px solid #E4E7ED;
  font-size: 14px;
  font-weight: bold;
  color: #303133;
}

.section-title i {
  margin-right: 6px;
  font-size: 16px;
}

/* 标签样式 */
.positive-label,
.negative-label,
.neutral-label,
.total-label,
.basic-label,
.calculated-label {
  display: flex;
  align-items: center;
  font-weight: 500;
}

.positive-label i,
.negative-label i,
.neutral-label i,
.total-label i,
.basic-label i,
.calculated-label i {
  margin-right: 4px;
  font-size: 14px;
}

.positive-label {
  color: #67C23A;
}

.negative-label {
  color: #F56C6C;
}

.neutral-label {
  color: #E6A23C;
}

.basic-label {
  color: #409EFF;
}

.calculated-label {
  color: #E6A23C;
}

.total-label {
  color: #E6A23C;
  font-size: 16px;
  font-weight: bold;
}

/* 计算结果区域特殊样式 */
.total-section {
  background: linear-gradient(135deg, #FFF7E6 0%, #FFF2D9 100%);
  border: 2px solid #E6A23C;
  box-shadow: 0 2px 8px rgba(230, 162, 60, 0.2);
}

/* 日工资输入框样式 */
.daily-salary-input .el-input__inner {
  color: #E6A23C;
  background-color: #FFFBF0;
  border: 1px solid #E6A23C;
  text-align: center;
  font-weight: 500;
}

.daily-salary-input .el-input-group__prepend {
  background-color: #E6A23C;
  color: white;
  border-color: #E6A23C;
}

/* 计算基本工资输入框样式 */
.calculated-salary-input .el-input__inner {
  color: #E6A23C;
  background-color: #FFFBF0;
  border: 1px solid #E6A23C;
  text-align: center;
  font-weight: 500;
}

.calculated-salary-input .el-input-group__prepend {
  background-color: #E6A23C;
  color: white;
  border-color: #E6A23C;
}

/* 综合工资输入框样式 */
.total-salary-input {
  font-size: 18px;
  font-weight: bold;
}

.total-salary-input .el-input__inner {
  font-size: 18px;
  font-weight: bold;
  color: #E6A23C;
  background-color: #FFFBF0;
  border: 2px solid #E6A23C;
  text-align: center;
}

.total-salary-input .el-input-group__prepend {
  background-color: #E6A23C;
  color: white;
  font-weight: bold;
  border-color: #E6A23C;
}

/* 输入框聚焦效果 */
.form-section .el-input-number.is-controls-right .el-input__inner:focus,
.form-section .el-input__inner:focus,
.form-section .el-textarea__inner:focus {
  border-color: #409EFF;
  box-shadow: 0 0 6px rgba(64, 158, 255, 0.2);
}

/* 表单项间距调整 */
.form-section .el-form-item {
  margin-bottom: 15px;
}

.form-section .el-form-item:last-child {
  margin-bottom: 0;
}

/* 对话框底部按钮样式 */
.dialog-footer {
  text-align: center;
  padding: 15px 0 0 0;
}

.dialog-footer .el-button {
  min-width: 100px;
  margin: 0 10px;
}

/* 响应式调整 */
@media (max-width: 900px) {
  .salary-dialog {
    width: 95% !important;
  }
  
  .form-section {
    padding: 10px;
  }
  
  .el-col {
    margin-bottom: 10px;
  }
}

@media (max-width: 768px) {
  .salary-dialog {
    width: 98% !important;
  }
  
  /* 在小屏幕上将出勤信息改为单列显示 */
  .form-section .el-row .el-col {
    width: 100% !important;
    margin-bottom: 15px;
  }
}
</style>
